let datas = [
  {
    id: 1,
    isCheck: false,
    goodName: '红米note7Pro',
    goodCount: 1,
    goodPrice: 1500,
  },
  { id: 2, isCheck: true, goodName: '红米K50', goodCount: 1, goodPrice: 2700 },
]

// 缓存DOM节点
let listEle, selectCountEle, priceAllEle, checkAllEle, selectDelEle

document.addEventListener('DOMContentLoaded', () => {
  listEle = document.getElementById('list')
  selectCountEle = document.getElementById('selectCount')
  priceAllEle = document.getElementById('priceAll')
  checkAllEle = document.getElementById('checkAll')
  selectDelEle = document.getElementById('selectDel')

  // 渲染页面数据
  renderDates()

  // 将点击事件代理给ul
  listEle.addEventListener('click', (event) => {
    // 删除所点击的商品
    if (event.target.className === 'del') {
      // getAttribute：获取自定义节点
      let goodId = event.target.getAttribute('del-id')
      delOne(goodId)
    }
    // 单选框
    if (event.target.className === 'check') {
      let goodId = event.target.getAttribute('check-id')
      checkOne(goodId)
    }
    // 减
    if (event.target.className === 'lose') {
      let goodId = event.target.parentElement.getAttribute('count-id')
      quantityChange('lose', goodId, 1)
    }
    // 加
    if (event.target.className === 'add') {
      let goodId = event.target.parentElement.getAttribute('count-id')
      quantityChange('add', goodId, 1)
    }
    // 输入框
    if (event.target.className === 'count') {
      inputValue(event)
    }
  }) //委托

  // 全选框
  checkedAll()

  //  删除被勾选的商品
  selectDelEle.addEventListener('click', delSelect)
}) // DOMContentLoaded的 不能删

// 构建全选框函数
function checkedAll() {
  let isChecked = false
  checkAllEle.addEventListener('click', () => {
    isChecked = !isChecked
    datas.forEach((data) => {
      data.isCheck = isChecked
      // 更新复选框状态后重新渲染数据
      renderDates()
    })
  })
}

// 构建单选框函数
function checkOne(goodId) {
  goodId = parseInt(goodId)
  let index = datas.findIndex((good) => good.id === goodId)
  datas[index].isCheck = !datas[index].isCheck
  // 更新单选框状态后重新渲染数据
  renderDates()
}

// 构建加减函数
function quantityChange(classname, goodId, number) {
  goodId = parseInt(goodId)
  let index = datas.findIndex((good) => good.id === goodId)
  if (classname === 'add') {
    datas[index].goodCount += 1
  } else {
    if (datas[index].goodCount <= 1) {
      return
    }
    datas[index].goodCount -= 1
  }
  renderDates()
}

// 构建输入的值同步到数据函数
function inputValue(event) {
  event.target.addEventListener('change', function () {
    let goodId = event.target.parentElement.getAttribute('count-id')
    goodId = parseInt(goodId)
    let index = datas.findIndex((good) => good.id === goodId)
    if (this.value < 0) {
      this.value *= -1
    } else {
      if (parseInt(this.value)) {
        datas[index].goodCount = this.value
      }
      renderDates()
    }
  })
}

// 构建删除所点击商品的函数：找到点击删除所在的数据的下标，通过splice()方法删除
function delOne(goodId) {
  goodId = parseInt(goodId)
  // 寻找下标
  let index = datas.findIndex((item) => item.id === goodId)
  // 删除
  datas.splice(index, 1)
  // 删除后重新渲染页面数据
  renderDates()
}

// 构建删除被勾选的商品函数：过滤掉已勾选的商品
function delSelect() {
  let newDatas = datas.filter((item) => item.isCheck === false)
  datas = newDatas
  // 删除后重新渲染页面数据
  renderDates()
}

// 构建页面数据渲染函数
function renderDates() {
  // 1、循环商品、创建li节点
  let liStr = ''
  if (datas.length === 0) {
    // 说明没有商品
    listEle.innerText = ''
    // 总数量和总价格设置为0
    selectCountEle.innerText = 0
    priceAllEle.innerText = 0
    // 全选框取消选中
    checkAllEle.checked = false
    return
  }

  datas.forEach((good) => {
    // 解构赋值：方便使用模板字符串
    let { id, isCheck, goodName, goodCount, goodPrice } = good
    liStr += `<li>
            <input type="checkbox" check-id=${id} class="check"  ${
      isCheck ? 'checked' : ''
    }/>
            <span>${goodName}</span>
            <div class="goodCount" count-id=${id}>
            <button class="lose">-</button>
            <input type="text" value="${goodCount}" class="count" />
            <button class="add">+</button>
            </div>
            <span class="onePrice">${goodPrice}</span>
            <span class="price">${goodCount * goodPrice}</span>
            <span class="del" del-id="${id}">删除</span>
        </li>`

    // 上树
    listEle.innerHTML = liStr
  })

  // 计算被勾选的商品数量：计算商品数据中isChecked为true的个数
  let selectNumber = datas.reduce((result, good) => {
    if (good.isCheck) {
      result += 1
    }
    return result
  }, 0)
  selectCountEle.innerText = selectNumber

  // 计算被勾选的商品的总价格：计算商品数据中isChecked为true的个数乘以商品的单价
  let totalPrice = datas.reduce((result, good) => {
    if (good.isCheck) {
      result += good.goodCount * good.goodPrice
    }
    return result
  }, 0)
  priceAllEle.innerText = totalPrice

  // 控制是否全选
  let isCheckAll = datas.every((good) => good.isCheck)
  checkAllEle.checked = isCheckAll
}

// 通过节点查找来找到商品的下标方法
//  给减号绑定事件
// if (event.target.className === 'lose') {
//   let clickName =
//     event.target.parentElement.previousElementSibling.innerText
//   let clickIndex = datas.findIndex((item) => item.goodName === clickName)
//   if (datas[clickIndex].goodCount) {
//     datas[clickIndex].goodCount--
//   }
//   // 减少后重新渲染页面数据
//   renderDates()
// }

// // 给加号绑事件
// if (event.target.className === 'add') {
//   let clickName =
//     event.target.parentElement.previousElementSibling.innerText
//   let clickIndex = datas.findIndex((item) => item.goodName === clickName)
//   datas[clickIndex].goodCount++
//   // 增加后重新渲染页面数据
//   renderDates()
// }

// // 给复选框绑定事件
// if (event.target.className === 'check') {
//   let clickName = event.target.nextElementSibling.innerText
//   let clickIndex = datas.findIndex((item) => item.goodName === clickName)
//   datas[clickIndex].isCheck = !datas[clickIndex].isCheck
//   // 删除后重新渲染页面数据
//   renderDates()
// }
